<template>
  <div class="profile-section">
    <div class="section-header">
      <h2 class="section-title">个人信息管理</h2>
      <p class="section-desc">管理您的基础信息和个人资料</p>
    </div>

    <!-- 头像和基础信息 -->
    <div class="profile-card">
      <div class="avatar-section">
        <div class="avatar-container">
          <a-avatar :size="120" :src="userInfo.avatar" class="user-avatar">
            {{ userInfo.nickname }}
          </a-avatar>
          <div class="avatar-actions">
            <a-button type="primary" size="small" @click="showAvatarModal = true">
              <CameraOutlined />
              更换头像
            </a-button>
          </div>
        </div>
        
        <div class="basic-info">
          <h3 class="user-name">{{ userInfo.nickname }}</h3>
          <p class="user-id">ID: {{ userInfo.id }}</p>
          <p class="register-time">注册时间: {{ userInfo.registerTime }}</p>
          <div class="user-role">
            <a-tag :color="getRoleColor(userInfo.role)">{{ getRoleText(userInfo.role) }}</a-tag>
          </div>
        </div>
      </div>
    </div>

    <!-- 详细信息编辑 -->
    <div class="info-form-card">
      <h3 class="card-title">详细信息</h3>
      <a-form
        :model="formData"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
        class="profile-form"
      >
        <a-form-item label="用户名/昵称" name="nickname">
          <a-input 
            v-model:value="formData.nickname" 
            placeholder="请输入用户名或昵称"
            :disabled="!editMode"
          />
        </a-form-item>
        
        <a-form-item label="真实姓名" name="realName">
          <a-input 
            v-model:value="formData.realName" 
            placeholder="请输入真实姓名"
            :disabled="!editMode"
          />
        </a-form-item>
        
        <a-form-item label="手机号码" name="phone">
          <a-input 
            v-model:value="formData.phone" 
            placeholder="请输入手机号码"
            :disabled="!editMode"
          >
            <template #suffix>
              <a-button v-if="editMode && formData.phone" type="link" size="small">
                验证
              </a-button>
            </template>
          </a-input>
        </a-form-item>
        
        <a-form-item label="邮箱地址" name="email">
          <a-input 
            v-model:value="formData.email" 
            placeholder="请输入邮箱地址"
            :disabled="!editMode"
          >
            <template #suffix>
              <a-button v-if="editMode && formData.email" type="link" size="small">
                验证
              </a-button>
            </template>
          </a-input>
        </a-form-item>
        
        <a-form-item label="个性签名" name="signature">
          <a-textarea 
            v-model:value="formData.signature" 
            placeholder="写点什么介绍一下自己吧..."
            :rows="3"
            :disabled="!editMode"
            :maxlength="200"
            show-count
          />
        </a-form-item>
        
        <a-form-item :wrapper-col="{ offset: 6, span: 18 }">
          <a-space>
            <a-button v-if="!editMode" type="primary" @click="enableEdit">
              <EditOutlined />
              编辑信息
            </a-button>
            <template v-else>
              <a-button type="primary" @click="saveProfile" :loading="saving">
                <SaveOutlined />
                保存修改
              </a-button>
              <a-button @click="cancelEdit">
                取消
              </a-button>
            </template>
          </a-space>
        </a-form-item>
      </a-form>
    </div>

    <!-- 头像上传模态框 -->
    <a-modal
      v-model:open="showAvatarModal"
      title="更换头像"
      width="500px"
      @ok="uploadAvatar"
      ok-text="确认上传"
      cancel-text="取消"
    >
      <div class="avatar-upload">
        <a-upload
          v-model:file-list="avatarFileList"
          name="avatar"
          list-type="picture-card"
          class="avatar-uploader"
          :show-upload-list="false"
          :before-upload="beforeUpload"
          @change="handleAvatarChange"
        >
          <div v-if="avatarUrl" class="avatar-preview">
            <img :src="avatarUrl" alt="avatar" />
          </div>
          <div v-else class="upload-placeholder">
            <PlusOutlined />
            <div class="upload-text">上传头像</div>
          </div>
        </a-upload>
        <div class="upload-tips">
          <p>• 支持 JPG、PNG 格式</p>
          <p>• 文件大小不超过 2MB</p>
          <p>• 建议尺寸 200x200 像素</p>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { 
  CameraOutlined, 
  EditOutlined, 
  SaveOutlined,
  PlusOutlined 
} from '@ant-design/icons-vue'
import { useLoginUserStore } from '@/store/user'

const loginUserStore = useLoginUserStore()

// 用户信息
const userInfo = ref({
  id: '123456789',
  nickname: '智源学者',
  avatar: '',
  registerTime: '2024-01-15',
  role: 'student'
})

// 表单数据
const formData = reactive({
  nickname: '智源学者',
  realName: '张三',
  phone: '138****8888',
  email: 'zhangsan@example.com',
  signature: '热爱学习，追求进步！'
})

// 编辑状态
const editMode = ref(false)
const saving = ref(false)
const originalData = ref({})

// 头像相关
const showAvatarModal = ref(false)
const avatarFileList = ref([])
const avatarUrl = ref('')

// 获取角色颜色
const getRoleColor = (role: string) => {
  const colors = {
    admin: 'red',
    teacher: 'blue',
    student: 'green'
  }
  return colors[role as keyof typeof colors] || 'default'
}

// 获取角色文本
const getRoleText = (role: string) => {
  const texts = {
    admin: '管理员',
    teacher: '教师',
    student: '学生'
  }
  return texts[role as keyof typeof texts] || '未知'
}

// 启用编辑模式
const enableEdit = () => {
  originalData.value = { ...formData }
  editMode.value = true
}

// 取消编辑
const cancelEdit = () => {
  Object.assign(formData, originalData.value)
  editMode.value = false
}

// 保存个人资料
const saveProfile = async () => {
  saving.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    message.success('个人信息更新成功！')
    editMode.value = false
  } catch (error) {
    message.error('更新失败，请重试')
  } finally {
    saving.value = false
  }
}

// 头像上传前验证
const beforeUpload = (file: File) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('只能上传 JPG/PNG 格式的图片!')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB!')
    return false
  }
  return false // 阻止自动上传
}

// 头像文件变化处理
const handleAvatarChange = (info: any) => {
  if (info.file) {
    const reader = new FileReader()
    reader.onload = (e) => {
      avatarUrl.value = e.target?.result as string
    }
    reader.readAsDataURL(info.file)
  }
}

// 上传头像
const uploadAvatar = async () => {
  if (!avatarUrl.value) {
    message.warning('请先选择头像图片')
    return
  }
  
  try {
    // 模拟上传
    await new Promise(resolve => setTimeout(resolve, 1000))
    userInfo.value.avatar = avatarUrl.value
    message.success('头像更新成功！')
    showAvatarModal.value = false
  } catch (error) {
    message.error('头像上传失败，请重试')
  }
}

onMounted(() => {
  // 初始化用户信息
  if (loginUserStore.loginUser.id) {
    userInfo.value = {
      ...userInfo.value,
      nickname: loginUserStore.loginUser.userName || '智源学者',
      avatar: loginUserStore.loginUser.userAvatar || ''
    }
    formData.nickname = loginUserStore.loginUser.userName || '智源学者'
  }
})
</script>

<style scoped>
.profile-section {
  max-width: 800px;
}

.section-header {
  margin-bottom: 24px;
}

.section-title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0 0 8px 0;
}

.section-desc {
  color: #666;
  margin: 0;
}

.profile-card {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
}

.avatar-section {
  display: flex;
  align-items: center;
  gap: 24px;
}

.avatar-container {
  text-align: center;
}

.user-avatar {
  background: linear-gradient(135deg, #20a1da 0%, #30a4ad 100%);
  color: white;
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 16px;
}

.avatar-actions {
  margin-top: 12px;
}

.basic-info {
  flex: 1;
}

.user-name {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin: 0 0 8px 0;
}

.user-id {
  color: #666;
  margin: 0 0 4px 0;
  font-family: 'Courier New', monospace;
}

.register-time {
  color: #666;
  margin: 0 0 12px 0;
}

.user-role {
  margin-top: 8px;
}

.info-form-card {
  background: white;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  padding: 24px;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0 0 24px 0;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.profile-form {
  max-width: 600px;
}

.avatar-upload {
  text-align: center;
}

.avatar-uploader {
  margin-bottom: 16px;
}

.avatar-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 6px;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100px;
  color: #999;
}

.upload-text {
  margin-top: 8px;
  font-size: 14px;
}

.upload-tips {
  text-align: left;
  color: #666;
  font-size: 12px;
  line-height: 1.5;
}

.upload-tips p {
  margin: 4px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .avatar-section {
    flex-direction: column;
    text-align: center;
    gap: 16px;
  }
  
  .profile-form {
    :deep(.ant-form-item-label) {
      text-align: left;
    }
  }
}
</style>
